import React, {PureComponent} from 'react';
// import { connect } from 'dva';
import style from "styled-components";
import {Form, Input, Button, Row, Col, Select, Icon, message} from 'antd';
import PFromUpload from "../../../components/Pro/PFromUpload";
import bcx_utils from "../../../common/bcx_utils";
import {
  getCertificationData,
  publicCommonDictGetDictByCodeTypes,
  enterpriseCompanyGetComIndustryinfo,
  enterpriseCompanyUpdateComAuthInfo,
  enterpriseCompanySendLegalAuthCode,
  enterpriseComAuthInfoCheckLegalAuthCode,
  enterpriseCompanyComIndustryGetIndustryconfigByIndustrytype
} from "../../../services/api";
import * as api from "../../../services/api";
// @connect(state => ({
//   monitor: state.monitor,
// }))
const FormItem = Form.Item;
const {Option} = Select;
@Form.create()

/**
 * 完善企业认证信息
 */
export default class InitialAuthenticationInformation extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      infos: {},//法人代表信息
      industryInfo: [],// 行业资质
      nationality: [],//国籍信息
      idCardType: [], //证件类型
      conf_safeRange: [], //安保范围
      comCerType: [],//证件类型
      comCerUrl: "",//工商注册信息 图片上传
      ifSendCode: false,//是否已经发送验证码
      count: 60,//验证码计时
      showIndustry: false
    };

  }

  /******************************生命周期******************************/

  componentDidMount = () => {
    this.publicCommonDictGetDictByCodeTypes();
  }


  /******************************ajax请求******************************/

    //查询字典> 企业信息> 获得行业信息配置字段
  publicCommonDictGetDictByCodeTypes = () => {
    let tmp = {codeTypes: ["nationality", "idCardType", "conf_safeRange", "comCerType"]};
    publicCommonDictGetDictByCodeTypes(tmp)
      .then(
        ({data: {nationality, idCardType, conf_safeRange, comCerType}}) => {

          this.setState({nationality, idCardType, conf_safeRange, comCerType});
          console.log(conf_safeRange, comCerType);
          return getCertificationData({}); //企业信息
        },
        (err) => {
          console.log(err);
        }
      )
      .then(
        ({data}) => {
          if (!data) {
            return;
          }
          console.log("企业信息",data);
          this.setState({
            infos: data,
          });
          return enterpriseCompanyComIndustryGetIndustryconfigByIndustrytype({industryType: data.industryType});//获得行业信息配置字段
        },
        (err) => {
          console.log(err);
        }
      )
      .then(
        (data) => {
          if (!data) {
            return;
          }
          console.log(data);
          if (data && data.data) {
            this.enterpriseCompanyGetComIndustryinfo();
            this.setState({showIndustry: true});
          }
        }, (err) => {
          console.log(err);
        }
      );
  }
  //企业信息-认证申请-行业资质查询
  enterpriseCompanyGetComIndustryinfo = () => {
    enterpriseCompanyGetComIndustryinfo({}).then(
      ({data}) => {
        console.log(data);
        if (!data || data.length === 0) {
          return;
        }
        this.setState({
          industryInfo: data
        });
        console.log(data);
      },
      (err) => {
        console.log(err);
      }
    );
  }

  //获取手机验证码
  enterpriseCompanySendLegalAuthCode = () => {
    const phone = this.props.form.getFieldValue("legalRepPhone");
    bcx_utils.preventRepeatAsync((callback) => callback((resolve) => {
      enterpriseCompanySendLegalAuthCode({t: "", sign: "", phone}).then(
        (data) => {
          console.log(data);
          resolve(false);
        },
        (err) => {
          console.log(err);
          resolve(false);
        }
      );
    }));
  }

  //手机验证===验证验证码，检查手机验证码和企业ID是否匹配，10分钟后验证码过期
  enterpriseComAuthInfoCheckLegalAuthCode = (resolve) => {
    const phone = this.props.form.getFieldValue("legalRepPhone");
    const code = this.props.form.getFieldValue("code");
    enterpriseComAuthInfoCheckLegalAuthCode({phone, code}).then((data) => {
      console.log(data);
      resolve(true);
    }, (err) => {
      console.log(err);
      // message.error(err.msg);
      resolve(false);
    });
  }


  /******************************相关事件******************************/
  /*********上传 */
  handleCancel = () => this.setState({previewVisible: false})
  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }
  handleChange = ({fileList}) => this.setState({fileList})


  //表单提交
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);

        let _this = this;
        this.validCode = false;//防止重复验证

        const ajaxValid = () => {
          return new Promise((resolve) => {
            _this.validCode = true;
            this.enterpriseComAuthInfoCheckLegalAuthCode(resolve);
          });
        };

        async function ajaxValidCode() {
          let ifValid = await ajaxValid();
          if (ifValid) {
            //修改企业认证信息
            _this.companyUpdate(values);
          }
        }

        if (this.validCode === false) {
          ajaxValidCode();
        }
      }
    });
  }

  //修改企业认证信息
  companyUpdate = (values) => {
    const {fixedAssets, annualTurnover, annualProfitTax} = this.state.infos;
    const ajax = {
      nationality: values.nationality,
      legalRepName: values.legalRepName,
      legalRepPhone: values.legalRepPhone,
      idCardType: values.idCardType,
      idCardNo: values.idCardNo,
      regAmount: values.regAmount,
      comCerType: values.comCerType,
      comCerNo: values.comCerNo,
      comCerUrl: values.comCerUrl,
      fixedAssets,
      annualTurnover,
      annualProfitTax,
      conf_safeRange: values.conf_safeRange,
      conf_securityLicenseNum: values.conf_securityLicenseNum,
      conf_securityLicenseUrl: values.conf_securityLicenseUrl,
    }
    console.log(ajax);
    bcx_utils.preventRepeatAsync((callback) => callback((resolve) => {
      //修改企业认证信息
      enterpriseCompanyUpdateComAuthInfo(ajax).then(
        ({msg}) => {
          // message.success(msg);
          this.props.nextStep();
          resolve();
        },
        (err) => {
          // message.error(err.msg);
          resolve();
        }
      );
    }))
  }


  //文件上传事件

  imageChange = (type, result) => {
    console.log(result);
    console.log(result.join());
    this.setState({[type]: result.join()});
  }

  //发送验证码
  sendCode = () => {
    const {ifSendCode} = this.state;
    const mobile = this.props.form.getFieldValue("legalRepPhone");
    const mobileError = this.props.form.getFieldError("legalRepPhone");
    //判断是否正确的手机号码，然后开始计时
    if (mobile !== undefined && mobileError === undefined) {
      if (ifSendCode) {
        return;
      } else {
        this.setState({ifSendCode: true});
        this.enterpriseCompanySendLegalAuthCode();
        this.codeTime = window.setInterval(() => {
          const {count} = this.state;
          if (count !== 1) {
            this.setState(preState => ({
              count: preState.count - 1,
            }));
          } else {
            clearInterval(this.codeTime);
            this.setState({ifSendCode: false, count: 10});
          }
        }, 1000);
      }
    } else {
      bcx_utils.preventRepeat(() => {
        message.error("请输入正确的手机号码", 1.8);
      }, 2000);
    }
  }

  /******************************render******************************/

    //国籍/地区
  renderNationality = () => {
    return this.state.nationality.map(val => (
      <Option
        value={val.codeValue + ""}
        key={val.codeValue}>{val.label}</Option>
    ));
  }


  //证件类型
  renderIdCardType = () => {
    console.log(this.state.idCardType);
    return this.state.idCardType.map(val => (
      <Option
        value={val.codeValue + ""}
        key={val.codeValue}>{val.label}</Option>
    ));
  }

  //证件类型
  renderIdComCerType = () => {
    return this.state.comCerType.map(val => (
      <Option
        value={val.codeValue + ""}
        key={val.codeValue}>{val.label}</Option>
    ));
  }
  //安保范围
  renderSecurityRange = () => {
    return this.state.conf_safeRange.map(val => (
      <Option
        value={val.codeValue + ""}
        key={val.codeValue}>{val.label}</Option>
    ));
  }

  //验证码
  renderValidButton = () => {
    const {ifSendCode, count} = this.state;
    if (ifSendCode) {
      return (
        <Button type="primary" disabled={ifSendCode}>
          {`${count} s`}
        </Button>
      );
    } else {
      return (
        <Button type="primary" className="getCaptcha" onClick={this.sendCode}
        >
          {'验证码'}
        </Button>
      );
    }
  }

  render() {
    /*********上传 */
    const {previewVisible, previewImage, fileList} = this.state;
    const {getFieldDecorator} = this.props.form;


    const uploadButton = (
      <div>
        <Icon type="plus"/>
        <div className="ant-upload-text">上传</div>
      </div>
    );


    const formItemLayout = {
      labelCol: {
        xs: {span: 6},
        sm: {span: 6},
      },
      wrapperCol: {
        xs: {span: 12},
        sm: {span: 12},
      },
    };
    const {
      legalRepName = "",
      legalRepPhone = "",
      nationality = "",
      idCardType = "",
      idCardNo = "",
      regAmount = "",
      comCerType = "",
      comCerNo = "",
      comCerUrl = "",
    } = this.state.infos;

    const {industryInfo, showIndustry} = this.state;

    //保安服务许可证号
    const findsecurityLicenseNum = () => {
      const result = industryInfo.find(val => val.fieldCode.trim() === "conf_securityLicenseNum");
      if (!result) {
        return "";
      } else {
        return result.fieldValue;
      }
    }
    //安保范围
    const findRange = () => {
      const result = industryInfo.find(val => val.fieldCode.trim() === "conf_safeRange");
      if (!result) {
        return [];
      }
      if (result.fieldValue == "") {
        return [];
      }
      return result.fieldValue.split(',');
    }
    //上传保安服务许可证
    const findSecurityLicenseUrl = () => {
      const result = industryInfo.find(val => val.fieldCode.trim() === "conf_securityLicenseUrl");
      if (!result) {
        return "";
      } else {
        return result.fieldValue;
      }
    }


    return (
      <Container>
        <header className="password-header">完善企业认证信息</header>
        {Object.keys(this.state.infos).length !== 0 && (
          <Form onSubmit={this.handleSubmit} style={{marginTop: 24}}
          >
            <Row>
              <Col span={6} className="authentication-sub-title">
                <span>法人代表信息</span>
              </Col>
            </Row>
            <FormItem {...formItemLayout} label="法人代表姓名"
            >
              {getFieldDecorator('legalRepName', {
                initialValue: legalRepName,
                rules: [{
                  required: true, message: '请输入法人代表姓名',
                }
                ],
              })(
                <Input placeholder="请输入" maxLength="30"/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="手机号码"
            >
              {getFieldDecorator('legalRepPhone', {
                initialValue: legalRepPhone,
                rules: [{
                  required: true, message: '请输入手机号码',
                }, {
                  pattern: /^1[0-9]{10}$/,
                  message: "手机号格式错误！"
                }],
              })(
                <Input placeholder="请输入" maxLength="11"/>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="验证码">
              <div style={{display: 'flex', marginTop: 5}}>
                {getFieldDecorator('code', {
                  rules: [{
                    required: true, message: '请输入验证码！',
                  }],
                })(
                  <Input placeholder="请输入"/>
                )}
                <div style={{width: 20, height: "100%"}}></div>
                {this.renderValidButton()}
              </div>
            </FormItem>

            <FormItem {...formItemLayout} label="国籍/地区"
            >
              {getFieldDecorator('nationality', {
                initialValue: nationality,
                rules: [{
                  required: true, message: '请输入国籍/地区',
                }],
              })(
                <Select placeholder="请选择">
                  {this.renderNationality()}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="证件类型"
            >
              {getFieldDecorator('idCardType', {
                initialValue: idCardType,
                rules: [{
                  required: true, message: '请输入证件类型',
                }],
              })(
                <Select placeholder="请选择">
                  {this.renderIdCardType()}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="证件号码"
            >
              {getFieldDecorator('idCardNo', {
                initialValue: idCardNo,
                rules: [{
                  required: true, message: '请输入证件号码',
                }, {
                  pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$)/,
                  message: "证件格式错误"
                }],
              })(
                <Input placeholder="请输入" maxLength="18"/>
              )}
            </FormItem>
            <Row>
              <Col span={6} className="authentication-sub-title">
                <span>工商注册信息</span>
              </Col>
            </Row>
            <FormItem {...formItemLayout} label="注册资金(万元)"
            >
              {getFieldDecorator('regAmount', {
                initialValue: regAmount,
                rules: [{
                  required: true, message: '请输入注册资金',
                }, {
                  pattern: /(^([1-9][0-9]{1,5}|0)(\.\d{1,4})*$)/,
                  message: '请以数字填写注册资金，例如：20000.0000万元（最大填写数字：999999.9999万元）',
                }],
              })(
                <Input placeholder="请输入"/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="证件类型"
            >
              {getFieldDecorator('comCerType', {
                initialValue: comCerType,
                rules: [{
                  required: true, message: '请输入证件类型',
                }],
              })(
                <Select placeholder="请选择">
                  {this.renderIdComCerType()}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="证件号"
            >
              {getFieldDecorator('comCerNo', {
                initialValue: comCerNo,
                rules: [{
                  required: true, message: '请输入证件号',
                }, {
                  pattern: /[0-9]/,
                  message: "证件格式错误"
                }],
              })(
                <Input placeholder="请输入" maxLength="18"/>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="上传营业执照"
            >
              <div className="clearfix">
                {getFieldDecorator('comCerUrl', {
                  initialValue: comCerUrl,
                  rules: [{
                    required: true, message: '请输上传营业执照',
                  }],
                })(
                  <PFromUpload num={2}/>
                )}

                <p>每张不超过:3M,格式为:jpg，jpeg，png</p>
                {/*<p style={{color: "#f5222d"}}>请上传附件</p>*/}
              </div>
            </FormItem>
            {showIndustry && (
              <div>
                <Row>
                  <Col span={6} className="authentication-sub-title">
                    <span>行业资质</span>
                  </Col>
                </Row>
                <FormItem {...formItemLayout} label="安保范围"
                >
                  {getFieldDecorator('conf_safeRange', {
                    initialValue: findRange(),
                    rules: [{
                      required: true, message: '请输入安保范围',
                    }],
                  })(
                    <Select
                      placeholder="请选择"
                      mode="multiple"
                      style={{width: '100%'}}
                    >
                      {this.renderSecurityRange()}
                    </Select>
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="保安服务许可证号"
                >
                  {getFieldDecorator('conf_securityLicenseNum', {
                    initialValue: findsecurityLicenseNum(),
                    rules: [{
                      required: true, message: '请输入保安服务许可证号',
                    }],
                  })(
                    <Input placeholder="请填写" maxLength="20"/>
                  )}
                </FormItem>

                <FormItem {...formItemLayout} label="上传保安服务许可证"
                >
                  <div className="clearfix">
                    {getFieldDecorator('conf_securityLicenseUrl', {
                      initialValue: findSecurityLicenseUrl(),
                      rules: [{
                        required: true, message: '请输上传营业执照',
                      }],
                    })(
                      <PFromUpload num={2}/>
                    )}
                    <p>每张不超过:3M,格式为:jpg，jpeg，png</p>
                  </div>
                </FormItem>
              </div>
            )}
            <FormItem {...formItemLayout} label=" " colon={false}
            >
              {/*<Button style={{marginRight: "8px"}}>取消</Button>*/}
              <Button className="submit" type="primary" htmlType="submit">保存</Button>
            </FormItem>
          </Form>
        )}


      </Container>
    );
  }
}


/*********************样式*************************** */
const Container = style.div`{
    .password-header{
        font-size: 20px;
        color: #333333;
        padding-bottom:16px;
        border-bottom:1px solid #e9e9e9;
    }
    .ant-btn-primary.getCaptcha{
        background-color: #0F71FF;
    }
    .authentication-sub-title{
        text-align:right;
        font-size: 16px;
        color: #333333;
        margin-bottom:24px;
    }
    .ant-upload-select-picture-card i {
        font-size: 32px;
        color: #999;
      }
      
      .ant-upload-select-picture-card .ant-upload-text {
        margin-top: 8px;
        color: #666;
      }
}`;
